package edu.byui.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

public class ClientSingleThread {

	private Socket clientSocket;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;
	private String username;
	private ArrayList<Message> messages;

	public static void main(String args[]) throws ClassNotFoundException {
		@SuppressWarnings("unused")
		ClientSingleThread c = new ClientSingleThread();
	}

	public ClientSingleThread() throws ClassNotFoundException{
		try{
			clientSocket = new Socket("localhost", 5555);
			oos = new ObjectOutputStream(clientSocket.getOutputStream());
			ois = new ObjectInputStream(clientSocket.getInputStream());
		}
		catch(Exception e){
			e.printStackTrace();
		}

		//Client gets input from user (a clients name)
		System.out.print("Enter your name: "); //prompt user for name
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //open up standard input

		try {
			username = br.readLine();
		} catch (IOException e) {
			System.out.println("Error trying to read your name!");
			System.exit(-1);
		}

		try {
			Command c = new Command("login", username);
			oos.writeObject(c);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		boolean keepAlive = true;
		String input;
		while (keepAlive) {
			System.out.println(username);
			System.out.println("Please choose from the items below:");
			System.out.println("n)\tNew Message");
			System.out.println("g)\tGet Messages");
			if (username.equals("root")) {
				System.out.println("c)\tClose the Server and Logout");
			}
			System.out.println("l)\tLogout\n");
			System.out.print("Enter a command: ");
			br = new BufferedReader(new InputStreamReader(System.in));
			try {
				input = br.readLine();

				if (input.equalsIgnoreCase("l")) {
					keepAlive = false;
					logout();
				}
				else if (input.equalsIgnoreCase("g")) {
					getMessages();
				}
				else if (input.equalsIgnoreCase("n")) {
					sendMessage();
				}
				else if (input.equalsIgnoreCase("c")) {
					Command c = new Command("close", username);
					oos.writeObject(c);
					System.out.println("Shutting Down SERVER!!!");
					oos.close();
					ois.close();
					clientSocket.close();
					keepAlive = false;
				}
			}
			catch (IOException e) {
				System.out.println("Error: There was a problem reading the input choise on the Client!");
				e.printStackTrace();
			}


		}

		System.out.println("Logging out");
		System.out.println("Done...");

		//Send input to server
		//Server uses input as a key to HashMap
		//If key exists, return Bean to client (display info), if not notify client that it doesn't exist
		//Start over again with step 2
	}
	private void sendMessage() throws IOException {
		System.out.println("Creating NEW MESSAGE:");
		System.out.print("TO: ");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String to = br.readLine();
		System.out.println("MESSAGE:");
		br = new BufferedReader(new InputStreamReader(System.in));
		String message = br.readLine();
		Message output = new Message(username, to, message);
		Command c = new Command("send", username, output);
		oos.writeObject(c);
	}
	private void logout() throws IOException {
		Command c = new Command("logout", username);
		oos.writeObject(c);
		oos.close();
		ois.close();
		clientSocket.close();
	}
	@SuppressWarnings("unchecked")
	private void getMessages() throws IOException, ClassNotFoundException {
		System.out.flush();
		System.out.println("Read...");
		System.out.println("n)\tNEW Messages");
		System.out.println("a)\tALL Messages");
		System.out.print("Please select an option: ");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input = br.readLine();
		while (true) {
			Command c = new Command("get", username);
			oos.writeObject(c);
			messages = (ArrayList<Message>) ois.readObject();
			if (input.startsWith("n")) {
				for (Message query: messages) {
					if (query.getRead() == 0) {
						if (query.getMessage().length() > 40) {
							System.out.println("<" + messages.indexOf(query) + ">\t"
									+ query.getMessage().substring(0, 40) + "...");
						}
						else if (query.getMessage().length() > 0) {
							System.out.println("<" + messages.indexOf(query) + ">\t"
									+ query.getMessage());
						}
						else {
							System.out.println("<" + messages.indexOf(query) + ">");
						}
					}
				}
			}
			else {
				for (Message query: messages) {
					if (query.getRead() == 0) {
						if (query.getMessage().length() > 40) {
							System.out.println("<" + messages.indexOf(query) + ">\t"
									+ query.getMessage().substring(0, 40) + "...");
						}
						else if (query.getMessage().length() > 0) {
							System.out.println("<" + messages.indexOf(query) + ">\t"
									+ query.getMessage());
						}
						else {
							System.out.println("<" + messages.indexOf(query) + ">");
						}
					}
					else {
						if (query.getMessage().length() > 40) {
							System.out.println(" " + messages.indexOf(query) + " \t"
									+ query.getMessage().substring(0, 40) + "...");
						}
						else if (query.getMessage().length() > 0) {
							System.out.println(" " + messages.indexOf(query) + " \t"
									+ query.getMessage());
						}
						else {
							System.out.println(" " + messages.indexOf(query));
						}
					}
				}
			}
			System.out.println("\n[Enter \"b\" to go back]");
			System.out.print("Message Number: ");
			br = new BufferedReader(new InputStreamReader(System.in));
			String in = br.readLine();
			if (in.equals("b")) {
				break;
			}
			else if (Integer.parseInt(in) < messages.size()) {
				dispMessage(Integer.parseInt(in));
			}
		}
	}
	private void dispMessage(int i) {
		System.out.flush();
		System.out.println("Message: " + i);
		System.out.println("FROM: " + this.messages.get(i).getFrom());
		System.out.println("TO: " + this.messages.get(i).getTo());
		System.out.println("SENT: " + this.messages.get(i).getSent().getTime().toString());
		System.out.println("Message ID: " + this.messages.get(i).getMessage_id());
		System.out.println("MESSAGE:");
		System.out.println(this.messages.get(i).getMessage());
		System.out.println("\n\n[Press ENTER to continue...]");
		if (messages.get(i).getRead() == 0) {
			Message num = new Message();
			num.setMessage_id(messages.get(i).getMessage_id());
			Command sendRead = new Command("read", username, num);
			try {
				this.oos.writeObject(sendRead);
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try {
			@SuppressWarnings("unused")
			String temp = br.readLine();
		}
		catch (IOException e) {
			// This line intentionally left blank.  (Thank you IBM)
		}
	}
}